<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\Originate;
class OriginateController extends Controller
{
    protected $fields = [
        'uid'=>'',
		'originate'=>'',
		'domain'=>'',
		'user_agent'=>'',
		'url'=>'',
		'status'=>'',
		'site_name'=>'',
		'wechat'=>'',
		'touch'=>'',
		'channel'=>'',
		'medium'=>'',
		'adverti_name'=>'',
		'adverti_content'=>'',
		'keyword'=>'',
		'terminal'=>'',
		'in_wechat'=>'',
		'adverti_type'=>'',
		'city'=>'',
		'ip'=>'',
    ];

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = array();
            $data['draw'] = $request->get('draw');
            $start = $request->get('start');
            $length = $request->get('length');
            $order = $request->get('order');
            $columns = $request->get('columns');
            $search = $request->get('search');
            $uid = auth()->user()->id;
            $neqIdCondition = [['id', '<>', $uid],];
            $data['recordsTotal'] = Originate::count();
            if (strlen($search['value']) > 0) {
               $data['recordsFiltered'] = Originate::where(function ($query) use ($search) {
                        $query->where('originate', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('url', 'like', '%' . $search['value'] . '%');
                    })->count();
               $data['data'] = Originate::where(function ($query) use ($search) {
                        $query->where('originate', 'LIKE', '%' . $search['value'] . '%')
                            ->orWhere('url', 'like', '%' . $search['value'] . '%');
                    })->skip($start)->take($length)
                        ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])->get();

            } else {
                $data['recordsFiltered'] = $data['recordsTotal'];
				$data['data'] = Originate::skip($start)->take($length)
					->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])->get();
            }
            return response()->json($data);
        }
        return view('admin.originate.index');
    }
	public function show($id)
    {
        //
    }
	/*
	*图形统计
	*/
	public function chart(Request $request){
		
		$data 				= [];
		$day				= 30;
		$start_time			= date("Y-m-d H:i:s", strtotime('-'.$day.'day'));
		$end_time			= date("Y-m-d H:i:s");
		$name				= '';
		$phone				= '';
		$wx					= '';
		$query				= '';
		$data['days']		= [];
		$data['counts']		= [];
		
		if ($request->isMethod('post')){
			$start_time		= $request->get('start_time');
			$end_time		= $request->get('end_time');
			$name			= $request->get('name');
			$phone			= $request->get('phone');
			$wx				= $request->get('wx');
			$query			= $request->get('query');
			$second1 		= strtotime($end_time);
			$second2 		= strtotime($start_time);
			$day			= floor(($second1 - $second2) / 86400);
			
		}
		$querys 			= Originate::select('id','created_at')->where('created_at','<=',$end_time)->where('created_at','>=',$start_time)
									->where('uid',auth()->user()->id)
									->where('name','like','%'.$name.'%')->where('phone','like','%'.$phone.'%')
									->where('wx','like','%'.$wx.'%')->where('query','like','%'.$query.'%')
									->get()->toArray();
		for($i=0;$i<=$day;$i++){
			$today 			= date("Y-m-d",strtotime($start_time)+86400*$i);//date("Y-m-d", strtotime(' -'. $i . 'day'));
			$data['days'][]	= date("m-d",strtotime($start_time)+86400*$i);
			$count			= 0;
			foreach($querys as $query){ 
				if(date('Y-m-d',strtotime($query['created_at'])) == $today){
					++$count;
				}
			}
			$data['counts'][]=$count;
		}
		$data['name']		= $name;
		$data['phone']		= $phone;
		$data['wx']			= $wx;
		$data['query']		= $query;
		$data['start_time']	= $start_time;
		$data['end_time']	= $end_time;
		return view('admin.query.chart',$data);
	}
	
	//表格统计模式
	public function table(Request $request){
		$uid 			= auth()->user()->id;
		$data 			= array();
		$data['t']		= isset($_GET['t'])?$_GET['t']:0;
		$data['url']	= '/admin/originate/table?v=1';
		$data['domain'] = '';
		$data['t']		= '';
		$data['tongji'] = '域名';
		$domain = 'domain';
		if(isset($_GET['domain'])){
			$domain 			= $_GET['domain'];
			$data['domain']		= '&domain='.$domain;
			switch($domain){
				case 'domain':
					$data['tongji'] = '域名';
					break;
				case 'originate':
					$data['tongji'] = '来源';
					break;
				case 'uid':
					$data['tongji'] = '推广员';
					break;
				case 'user_agent':
					$data['tongji'] = '浏览器类型';
					break;
				case 'site_name':
					$data['tongji'] = '站点名称';
					break;
				case 'wechat':
					$data['tongji'] = '微信';
					break;
				case 'touch':
					$data['tongji'] = '点击事件';
					break;
				case 'channel':
					$data['tongji'] = '渠道';
					break;
				case 'medium':
					$data['tongji'] = '媒介';
					break;
				case 'adverti_name':
					$data['tongji'] = '广告名称';
					break;
				case 'adverti_content':
					$data['tongji'] = '广告内容';
					break;
				case 'keyword':
					$data['tongji'] = '关键词';
					break;
				case 'terminal':
					$data['tongji'] = '终端';
					break;
				case 'in_wechat':
					$data['tongji'] = '是否在微信内';
					break;
				case 'adverti_type':
					$data['tongji'] = '形式';
					break;
				case 'city':
					$data['tongji'] = '城市';
					break;
				case 'ip':
					$data['tongji'] = 'ip';
					break;
			}
		}
		if(isset($_GET['t'])){
				$data['t']			= '&t='.$_GET['t'];
			}
        if ($request->ajax()) {
            $data['draw'] 			= $request->get('draw');
            $start 					= $request->get('start');
            $length 				= $request->get('length');
            $order 					= $request->get('order');
            $columns 				= $request->get('columns');
            $search 				= $request->get('search');
            $data['recordsTotal'] 	= Originate::where('uid',$uid)->count();
			if(isset($_GET['t'])){
				if($_GET['t']=='today'){
					$start_time 		= date('Y-m-d H:i:s',strtotime(date('Y-m-d', time())));
				}else{
					$start_time 		= date('Y-m-d H:i:s', strtotime("-".(int)$_GET['t']." minutes"));
				}
				
				$end_time			= date('Y-m-d H:i:s');
				$querys 			= Originate::where('uid',$uid)->where('created_at',">",$start_time)->where('created_at',"<=",$end_time)->get();
			}else{
				$querys 			= Originate::where('uid',$uid)->get();
			}
			$data_arr2 				= [];
			$data_count 			= [];
			foreach($querys as $query){
				if(!isset($data_arr2[$query->$domain])){
					$data_arr2[$query->$domain] = [];//创建行
				}
				foreach (array_keys($this->fields) as $field) {
					if(!isset($data_arr2[$query->$domain][$field."_count"])){
						$data_arr2[$query->$domain][$field."_count"] = 0;//创建列
					}
					if(!isset($data_count[$field."_count"])){
						$data_count[$field."_count"] = 0;//创建该列的总数
					}
					if($query->$field!=null){
						$data_arr2[$query->$domain][$field."_count"] = $data_arr2[$query->$domain][$field."_count"]+1;
						$data_count[$field."_count"] = $data_count[$field."_count"]+1;
					}
				}
			}
			$data_arr 				= [];
			$data_arr3 				= [];
			foreach($data_arr2 as $da2k=>$da2){
				$data_arr['domain'] = $da2k;
				foreach (array_keys($this->fields) as $field){
					$data_arr[$field."_count"] 		= $da2[$field."_count"];
					if($data_count[$field."_count"]!=0){
						$data_arr[$field."_bfb"] 	= round($da2[$field."_count"]/$data_count[$field."_count"],4)*100;
					}else{
						$data_arr[$field."_bfb"] 	= 0;
					}
				}
				$data_arr3[] 		= $data_arr;
			}
			
			$data_arr4 				= [];
			foreach($data_arr3 as $da3k=>$da3){
				if($da3k>=$start&&$da3k<$start+$length)
				$data_arr4[] 		= $da3;
			}
			$data['data']			= json_decode(json_encode($data_arr4));
			$data['recordsFiltered']= count(json_decode(json_encode($data_arr3)));
            return response()->json($data);
        }
		return view('admin.originate.table',$data);
	}
	
	//分列
	public function edit(Request $request,$id=0){
		$tags = Originate::where('uid',auth()->user()->id)->where('status',0)->limit(10)->get();
		$data2 = [];
		$notPictures_count = 0;
		foreach($tags as $tag){ 
			$arr			= GetIpLookup($tag->ip);
			$tag->city 		= $arr['province'].$arr['city'];
			$tag->terminal 	= check_system($tag->user_agent)." ".check_browser($tag->user_agent);
			//$tag->touch		= getTouch($tag->originate);
			$tag->keyword	= getKeyword($tag->originate);
			$tag->status	= 1;
			$tag->channel	= getChannel($tag->originate);//渠道
			$notPictures_count++;
			$tag->save();
			//check_device($tag->user_agent);
		}
		//Originate::where('uid',auth()->user()->id)->where('status',0)->update($data2);
		echo date('Y-m-d H:i:s')." 已更新".$notPictures_count."条数据，继续更新......";
		if($notPictures_count>=10){
			echo "<script>location.reload();</script>";	
		}else{
			echo "更新完成！<script type='text/javascript'>function refresh(){ window.location.reload();  } setTimeout('refresh()', 5000);</script>";
		}
	}
	
	
}

